<template>
  <div>
    <el-dialog
      :title="model.id ? '修改信息' : '新增信息'"
      :visible.sync="showModal"
      width="800"
      center
      :close-on-click-modal="false"
    >
      <el-form :model="model" :rules="rules" ref="ruleForm" label-width="115px" class="demo-ruleForm el-form-col">
        <el-row v-if="!model.id">
          <el-col :span="8">
            <el-form-item label="姓名:">
              <el-autocomplete
                class="inline-input"
                v-model="searchWorker"
                :fetch-suggestions="querySearch"
                placeholder="请输入师傅名称"
                :trigger-on-focus="false"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名:" prop="workerName">
              <el-input v-model="model.workerName" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录账号:" prop="logAccount">
              <el-input v-model="model.logAccount" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系手机:" prop="phone">
              <el-input v-model="model.phone">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务类型:" prop="businessNo">
              <el-checkbox-group v-model="model.businessNo">
                <el-checkbox v-for="item of businessArr" :label="item.value" :key="item.value">{{item.text}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务类型:" prop="serviceNo">
              <el-checkbox-group v-model="model.serviceNo">
                <el-checkbox v-for="item of serviceArr" :label="item.value" :key="item.value">{{item.text}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务省市:" prop="address">
              <Cascade-address changeOnSelect v-model="model.address" :level="2"></Cascade-address>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="覆盖服务区县:" prop="districtNo">
              <el-checkbox :indeterminate="isIndeterminate"
                           v-model="checkAll"
                           @change="handleCheckAllChange"
                           v-if="districtArr.length"
              >全选</el-checkbox>
              <el-checkbox-group v-model="model.districtNo" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="item of districtArr" :label="item.areaNo" :key="item.areaNo">{{item.areaName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hide">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CascadeAddress from '@/components/CascadeAddress'
import {getInstallBusinessType, getInstallServiceType} from '@/utils/selectOptions'
import {isEqual, copy} from '@/utils'
import {isPhone} from '@/utils/validate'
export default {
  name: 'workerModal',
  components: {
    CascadeAddress
  },
  data() {
    return {
      detail: {},
      showModal: false,
      loading: false,
      restaurants: [],
      searchWorker: '',
      isIndeterminate: false,
      checkAll: false,
      model: {
        workerName: '',
        logAccount: '',
        phone: '',
        businessNo: [],
        serviceNo: [],
        address: [],
        districtNo: []
      },
      businessArr: [],
      serviceArr: [],
      checkList: [],
      districtArr: [],
      rules: {
        workerName: [
          { required: true, message: '请选择师傅', trigger: 'change' }
        ],
        logAccount: [
          { required: true, message: '请选择师傅', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: isPhone, message: '手机号格式有误', trigger: 'blur' }
        ],
        businessNo: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        serviceNo: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请选择服务省市', trigger: 'change' }
        ],
        districtNo: [
          { required: true, message: '请选择服务区域', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    getInstallBusinessType().then(arr => {
      this.businessArr = arr
    })
    getInstallServiceType().then(arr => {
      this.serviceArr = arr
    })
  },
  watch: {
    'model.address'(val, oldVal) {
      this.districtArr = []
      if (isEqual(val, oldVal) || val.length !== 2) {
        return
      }
      this.getDistrict(val[1])
    }
  },
  methods: {
    show(data) {
      this.showModal = true
      this.$nextTick(_ => {
        this.$refs['ruleForm'].resetFields()
        this.clear()
        this.upDate(data)
      })
    },
    hide() {
      this.showModal = false
    },
    clear() {
      this.loading = false
      this.searchWorker = ''
      this.model.id = ''
    },
    upDate(data) {
      if (!data) {
        return
      }
      this.model.workerName = data.workerName
      this.model.logAccount = data.logAccount
      this.model.phone = data.phone
      this.model.businessNo = data.businessNo.split(',')
      this.model.serviceNo = data.serviceNo.split(',')
      this.model.address = []
      this.model.address.push(data.provinceNo)
      this.model.address.push(data.cityNo)
      this.model.districtNo = data.districtNo.split(',')
      this.model.id = data.id
    },
    handleSelect(item) {
      this.model.workerName = item.workerName
      this.model.logAccount = item.logAccount
      this.model.workerId = item.workerId
    },
    handleCheckAllChange(val) {
      if (val) {
        this.model.districtNo = []
        this.districtArr.forEach(item => {
          this.model.districtNo.push(item.areaNo)
        })
      } else {
        this.model.districtNo = []
      }
    },
    handleCheckedCitiesChange(value) {
      if (this.districtArr.length === value.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    querySearch(queryString, cb) {
      this.getWorker(queryString).then(response => {
        response.forEach(item => {
          // 做一下映射
          item.workerName = item.name
          item.workerId = item.userId
          item.logAccount = item.registerPhone
          item.value = item.workerName
        })
        cb(response)
      })
    },
    getWorker(val) {
      return this.$ajax.get('/ms-fahuobao-app/workerUser/getWorkerByName', {name: val, mark: 1}).then(response => {
        return (response.data || [])
      })
    },
    getDistrict(val) {
      this.$ajax.get('/ms-address/address/findByParentNo', {parentNo: val}).then(response => {
        this.districtArr = response.data || []
      })
    },
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return
        }
        let data = copy(this.model, true)
        if (data.address.length) {
          data.provinceNo = data.address[0]
          data.cityNo = data.address[1]
        }
        data.businessNo = data.businessNo.toString()
        data.serviceNo = data.serviceNo.toString()
        data.districtNo = data.districtNo.toString()
        delete data.address
        if (this.model.id) {
          data.operation = 'update'
        } else {
          data.operation = 'insert'
        }
        this.loading = true
        this.$ajax.post('/ms-warehouse-order/resourceManage/operateInstall', data).then(response => {
          this.loading = false
          if (response.success) {
            this.hide()
            this.$emit('refresh')
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
          }
        })
      })
    }
  }
}
</script>
